#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod ui;
mod config;

use std::{fs::File, io::Read, net::{IpAddr, SocketAddr}};

use config::Config;
use ui::ChatUI;
use iced::{Application, Settings};

static mut DEFAULT_FONT: Option<&[u8]> = None;

static mut REMOTE_ROOM_ADDR: Option<SocketAddr> = None;

pub fn main() {
    init_config();

    let mut settings = Settings::default();
    settings.default_font = unsafe { DEFAULT_FONT };
    settings.window.size = (400, 650);
    ChatUI::run(settings).unwrap();
}

fn init_config() {
    let config: Option<Config> = {
        let file = File::open("MoyuConfig.toml");
        if let Ok(mut file) = file {
            let mut f = String::new();
            file.read_to_string(&mut f).unwrap();

            toml::from_str(f.as_str()).ok()
        } else {
            None
        }
    };

    if let Some(config) = config {
        let font = if let Some(font) = config.font {
            File::open(font.path)
        } else {
            File::open("font.otf")
        };

        if let Ok(mut f) = font {
            let mut buf = Vec::new();
            f.read_to_end(&mut buf).unwrap();
    
            unsafe {
                DEFAULT_FONT.replace(Box::leak(buf.into_boxed_slice()));
            }
        }

        if let Some(remote) = config.remote  {
            if let Some(port) = remote.port {
                unsafe {
                    REMOTE_ROOM_ADDR.replace(SocketAddr::new(remote.addr.parse().unwrap(), port));
                }
            }
        };
    }
}